package com.monitorRoutine.monitorRoutineController.service.impl;

import com.alibaba.fastjson.JSON;
import com.monitorRoutine.monitorRoutineController.Initialize;
import com.monitorRoutine.monitorRoutineController.entity.MonitorComputerProcess;
import com.monitorRoutine.monitorRoutineController.entity.MonitorProcessResult;
import com.monitorRoutine.monitorRoutineController.service.ExecuteCommandService;
import com.monitorRoutine.monitorRoutineController.service.MonitorProcessService;
import jdk.nashorn.internal.parser.JSONParser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class MonitorProcessServiceImpl implements MonitorProcessService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    ExecuteCommandService executeCommandService;
    private static final long EXPIRATION_SECONDS = 60 * 10; // 例如：设置过期时间为1小时

    @Override
    public void scanProcess() {

        String NAME = Initialize.configurationMapper.get("monitorRoutineController.format.name");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
        String name_process = NAME+"_process";
        List<String> processNameList = redisTemplate.opsForList().range(name_process, 0, -1);
        List<String> generalNameList = redisTemplate.opsForList().range("general_process", 0, -1);


        Set<String> set = new LinkedHashSet<>(processNameList);
        set.addAll(generalNameList);

        HashMap<String, String> restMap = new HashMap<>();



        for (String s : set) {
            MonitorComputerProcess monitorComputerProcess = JSON.parseObject(s, MonitorComputerProcess.class);
            MonitorProcessResult monitorProcessResult = new MonitorProcessResult();


            LocalDateTime now = LocalDateTime.now();
            String formattedDateTime = now.format(formatter);


            monitorProcessResult.setProcessRelationid(monitorComputerProcess.getId());
            monitorProcessResult.setProcessiname(monitorComputerProcess.getProcessiname());
            monitorProcessResult.setComputername(NAME);
            Boolean b = executeCommandService.processExists(monitorComputerProcess.getProcessiname());
            monitorProcessResult.setResult(b.toString());
            monitorProcessResult.setCompletiontime(formattedDateTime);



            String string = JSON.toJSONString(monitorProcessResult);
            restMap.put(monitorComputerProcess.getProcessiname(),string);
        }

        redisTemplate.opsForHash().putAll(NAME+"_processResult", restMap);
    }
}
